//
//  AppDelegate.m
//  laziz_Consumer
//
//  Created by XMac on 16/10/21.
//  Copyright © 2016年 XMac. All rights reserved.
//

#import "AppDelegate.h"
#import "CityManager.h"
#import "TShareEventHandler.h"
#import "LZMapLocationManager.h"
#import "LZUserModel.h"
#import "JPUSHService.h"
#import "LZNotificationPresenter.h"
#import "UMMobClick/MobClick.h"
#import "IQKeyboardManager.h"
#import "LZLeadingView.h"
#import "LZLeadingViewPresenter.h"
#import "LZHomePageViewController.h"
#import "UITabBar+LZBadge.h"
#import "LZUserInfoPresenter.h"
#import "extobjc.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@import GoogleMaps;

@interface AppDelegate ()<JPUSHRegisterDelegate>

@property (nonatomic, strong) NSData *deviceToken;
@property (nonatomic, strong) LZNotificationPresenter *notificationPresenter;
@property (nonatomic, strong) LZUserInfoPresenter *userPresenter;

@end

@implementation AppDelegate



#pragma
#pragma mark#pragma

#pragma
#pragma mark base configuration setup
-(void)setupBaseConfig{
    /*
     ==========================================uuid=================================================
     */
    NSString *first = [[NSUserDefaults standardUserDefaults] objectForKey:@"first"];
    if (first == nil) {
        NSString *uuid = [self getUUID];
        [[NSUserDefaults standardUserDefaults] setObject:@"first" forKey:@"first"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"uuid"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
}

#pragma
#pragma mark private method
/**
 *  @author taohebin, 16-08-22 14:08:32
 *
 *  获取uuid值
 *
 */
- (NSString*)getUUID {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}

#pragma mark config UI
-(void)configAppUI{
    /*
     ==========================================UINavigationBar appearance=================================================
     */
    // ********************** 全局设置返回按钮样式 **********************
    UINavigationBar * navigationBar = [UINavigationBar appearance];
    
    //返回按钮的箭头颜色
    
    [navigationBar setTintColor:[UIColor clearColor]];
    
    //设置返回样式图片
    
    NSString *backImageName = @"返回键_头部";
    if ([LZLanguageManager shareInstance].getLanguageType == LanguageType_Ar && ([[[UIDevice currentDevice] systemVersion] floatValue] >=9.0)) {
        backImageName = @"返回键_头部_ar";
    }
    
    UIImage *backImage = [UIImage imageNamed:backImageName];
    
    backImage = [backImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    navigationBar.backIndicatorImage = backImage;
    
    navigationBar.backIndicatorTransitionMaskImage = backImage;
    
    //将返回按钮的文字position设置不在屏幕上显示
    if ([[UIDevice currentDevice].systemVersion integerValue]<11) {
        [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    }
    
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0x333333, 1)}];
    
    [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setShadowImage:[self createImageWithColor:UIColorFromRGB(0xcccccc, 1) size:CGSizeMake(0.5, 0.5)]];
        
    /*
     ==========================================UISearchBar appearance=================================================
     */
    [[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:UIColorFromRGB(0x666666, 1)];
    
    /*
     ==========================================UITabBar appearance=================================================
     */
    UIView *view = [[UIView alloc] init];
//    view.backgroundColor = UIColorFromRGB(0x000000, 0.7);
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH, 49);
    [[UITabBar appearance] insertSubview:view atIndex:0];
    
    // 添加毛玻璃view
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = view.bounds;
    [view addSubview:effectView];
    
    // 添加上边的线
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
    line.backgroundColor = UIColorFromRGB(0xd7d7d7, 1);
    [view addSubview:line];
    
    UIImage *clearImage = [self createImageWithColor:[UIColor clearColor] size:CGSizeMake(1, 1)];
    [[UITabBar appearance] setShadowImage:clearImage];
    [[UITabBar appearance] setBackgroundImage:clearImage];
    
    // 设置title的颜色和大小
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0x333333, 1),NSForegroundColorAttributeName:[UIFont systemFontOfSize:12]} forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0xff7a21, 1),NSForegroundColorAttributeName:[UIFont systemFontOfSize:12]} forState:UIControlStateSelected];
    /*
     ========================================== 设置TabBarItem图片 =================================================
     */
    
    UITabBarController *tabBarController = (UITabBarController*)self.window.rootViewController;
    UITabBar *tabBar = tabBarController.tabBar;
    UITabBarItem *tabBarItem0 = tabBar.items[0];
    UITabBarItem *tabBarItem1 = tabBar.items[1];
    UITabBarItem *tabBarItem2 = tabBar.items[2];

//    CGFloat offset = SCREEN_WIDTH/375.0*185/2.0-SCREEN_WIDTH/6.0;
//    if ([LZLanguageManager shareInstance].getLanguageType == LanguageType_Ar && ([[[UIDevice currentDevice] systemVersion] floatValue] >=9.0)) {
//        offset *= -1;
//    }
    
    CGFloat titleOffset_y = -3;
    
    tabBarItem0.title = LZLocalizedString(@"tabbar_home", nil);
    [tabBarItem0 setTitlePositionAdjustment:UIOffsetMake(0, titleOffset_y)];
    tabBarItem0.selectedImage = [[UIImage imageNamed:@"首页_点击"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    tabBarItem0.image = [[UIImage imageNamed:@"首页_未点击"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    tabBarItem0.imageInsets = UIEdgeInsetsMake(7, offset, -7, -offset);

    tabBarItem1.title = LZLocalizedString(@"tabbar_restaurant", nil);
    [tabBarItem1 setTitlePositionAdjustment:UIOffsetMake(0, titleOffset_y)];
    tabBarItem1.selectedImage = [[UIImage imageNamed:@"餐厅_高亮"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    tabBarItem1.image = [[UIImage imageNamed:@"餐厅_默认"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    tabBarItem1.imageInsets = UIEdgeInsetsMake(7, 0, -7, 0);

    tabBarItem2.title = LZLocalizedString(@"tabbar_myaccount", nil);
    [tabBarItem2 setTitlePositionAdjustment:UIOffsetMake(0, titleOffset_y)];
    tabBarItem2.selectedImage = [[UIImage imageNamed:@"我的_点击"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    tabBarItem2.image = [[UIImage imageNamed:@"我的_未点击"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    tabBarItem2.imageInsets = UIEdgeInsetsMake(7, -offset, -7, offset);

}


-(void)configAppLeadingViewWithOptions:(NSDictionary *)launchOptions {
    /*
     ==========================================Leading View=================================================
     */
    LZLeadingView *leadingView = [[LZLeadingView alloc] initWithFrame:self.window.bounds];
    [self.window.rootViewController.view addSubview:leadingView];
    
    WS(weakSelf)
    leadingView.dismissLeadingViewBlock = ^() {
        
        [LZLeadingViewPresenter storNowVersionNum];
        
        [weakSelf registerAppService];
        [weakSelf configJPushWithOptions:launchOptions];
        UITabBarController *tabbarController = (UITabBarController*)weakSelf.window.rootViewController;
        UINavigationController *navController = (UINavigationController*)tabbarController.selectedViewController;
        LZHomePageViewController *homeVC = navController.viewControllers.firstObject;
        [homeVC startLocationService];
    };
}

- (void)configIQKeyboard {
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].shouldShowTextFieldPlaceholder = NO;
}

-(UIImage*) createImageWithColor:(UIColor*) color size:(CGSize)size
{
    CGRect rect=CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

-(void)registerAppService{
    
    [GMSServices provideAPIKey:@"AIzaSyDVJkTzmzVYiQa11oS7oX93Ke1d5bfFeIg"];
}

- (void)setupShareService:(NSDictionary *)launchOptions {
    
    [TShareEventHandler setupShareSDK:launchOptions];
}

- (void)configMobClick {
    UMConfigInstance.appKey = @"582c378275ca35159f001e58";
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];
    
    //配置版本
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
}

/*
- (void)languageChanged:(NSNotification*)notification
{
    NSString *lan = [UIApplication sharedApplication].delegate.window.textInputMode.primaryLanguage;
    if ([lan isEqualToString:@"en-US"]) {
        [CityManager shareManager].boardLanguage = kLanguage_EN;
    }else if ([lan isEqualToString:@"zh-Hans"]){
        [CityManager shareManager].boardLanguage = kLanguage_CH;
    }else if ([lan isEqualToString:@"ar"]){
        [CityManager shareManager].boardLanguage = kLanguage_AR;
    }else{
        [self configureLanguageForSystem];
    }
    
}
*/

- (void)configureCityManager
{
//    [[LZMapLocationManager shareLocationManager] appStartLocationServer];
}

- (void)configUserInfo {
    [[LZUserModel Instance] updateUserInfoIfNeeded];
}

#pragma mark - config JPush
- (void)configJPushWithOptions:(NSDictionary *)launchOptions {
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
            if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
              NSSet<UNNotificationCategory *> *categories;
              entity.categories = categories;
            }
            else {
              NSSet<UIUserNotificationCategory *> *categories;
              entity.categories = categories;
            }
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService setupWithOption:launchOptions appKey:@"a24960009d16d405584a96d3"
                          channel:@"AppStore"
                 apsForProduction:YES];

    self.notificationPresenter = [[LZNotificationPresenter alloc] init];

    // 透传
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
}

/* 透传接收到的消息 */
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    [self.notificationPresenter dealNotificationWithDictionary:userInfo];
    
}


#pragma mark - action
- (void)showTabbarBadge
{
    UITabBarController *tabBarController = (UITabBarController*)self.window.rootViewController;
    [tabBarController.tabBar showBadgeOnItemIndex:2];
}

- (void)hiddenTabbarBadge
{
    UITabBarController *tabBarController = (UITabBarController*)self.window.rootViewController;
    [tabBarController.tabBar hideBadgeOnItemIndex:2];
}

- (void)homeVCChangeDatasourceWhenUserLogout
{
    UITabBarController *tabbarController = (UITabBarController*)[UIApplication sharedApplication].delegate.window.rootViewController;
    for (UINavigationController *nav in tabbarController.viewControllers) {
        for (UIViewController *vc in nav.viewControllers) {
            if ([vc isKindOfClass:[LZHomePageViewController class]]) {
                [(LZHomePageViewController *)vc changeDatasoucreWhenUserLogout];
            }
        }
    }
}

+ (NSData*)getDeviceToken {
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    return appDelegate.deviceToken;
}


#pragma
#pragma mark - UIApplicationDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    /* ❗️❗️❗️❗️❗️❗️❗️❗️ 所有需要调用权限的都需要先判断是否显示引导页，如果显示引导页，则在引导页消失后调用 ❗️❗️❗️❗️❗️❗️❗️❗️ */
    
    [[LZLanguageManager shareInstance] initUserLanguage];
    
    [self setupBaseConfig];
    
    [self configAppUI];
    
    [self setupShareService:launchOptions];
    
    [self configMobClick];
    
    [self configureCityManager];
    
    [self configUserInfo]; //如果用户登录，app启动更新用户信息
    
    [self configIQKeyboard];
    
    BOOL isShowLeadingView = [LZLeadingViewPresenter isShowLeadingView];
    
    if (isShowLeadingView) {
        [self configAppLeadingViewWithOptions:launchOptions];
    }
    else {
        [self registerAppService];
        [self configJPushWithOptions:launchOptions];
    }

    /*//====第一版暂时不考虑键盘语言与系统语言不同的情况
    NSNotificationCenter *notf = [NSNotificationCenter defaultCenter];
    [notf addObserver:self selector:@selector(languageChanged:) name:UITextInputCurrentInputModeDidChangeNotification object:nil];
    */
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    //    [APService stopLogPageView:@"aa"];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // 这里应该添加新的接口,专门去请求用户是否有未读消息.因为用户在app后台时,有可能处于很多种情况.所以应该单独加接口验证.来确定是否要显示用户中心小红点
    if (_userPresenter == nil) {
        _userPresenter = [[LZUserInfoPresenter alloc] init];
    }
    
    @weakify(self);
    [self.userPresenter checkUserHaveUnReadMsg:^(NSInteger unReadCount) {
        @strongify(self);
        if (unReadCount > 0) {
            [self showTabbarBadge];
        }else{
            [self hiddenTabbarBadge];
        }
    } failure:^(NSString *fail) {
       @strongify(self);
        [self hiddenTabbarBadge];
    }];
}

- (void)applicationWillTerminate:(UIApplication *)application {
   
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
   
    DLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
    self.deviceToken = deviceToken;
    [LZNotificationPresenter setNotificationAlias:[LZUserModel Instance].userId];
    DLog(@"🌂🌂userid🌂🌂 = %@",[LZUserModel Instance].userId)
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    DLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // iOS6及以下系统，收到通知
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    // iOS7及以上系统，收到通知
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:-1];
    
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    [self.notificationPresenter operationPushWhenAppInDeskWithInfo:userInfo];
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:-1];
    
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        
        [self.notificationPresenter operationPushToVCWithInfo:userInfo];
        
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}
#endif


@end
